package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)  // 导入配置
public class AuthController {

    @Autowired
    private JwtProperties pro;

    @Autowired
    private AuthService authService;

    /**
     * 登录授权的方法
     *
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        // 在server里使用fen调用user里的方法去查询用户和密码在数据库里是否正确，并返回token
        String token = this.authService.authentication(username, password);
        if (StringUtils.isBlank(token)) {
            // 如果token不存在为空
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);  // 未经许可
        }
        // 如果认证成功,将加密好的token放到cookie里,其实就是调用了setCookie的方法
        // 返回给客户端，最后一个参数getExpire要*60
        CookieUtils.setCookie(request, response, this.pro.getCookieName(), token, pro.getExpire() * 60);
        return ResponseEntity.ok(null);
    }

    /**
     * 根据客户端请求过来的token验证用户
     *
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN") String token,
                                               HttpServletRequest request,
                                               HttpServletResponse response) {
        try {
            // 通过jwt工具类使用公钥从token中解密数据返回
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.pro.getPublicKey());
            if (userInfo == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }

            // 认证成功后，重新生成token,刷新有效时间，这个Expire是30分钟,旧的token就放到黑名单了
            token = JwtUtils.generateToken(userInfo, this.pro.getPrivateKey(), this.pro.getExpire());

            // 更新cookie中的有效时间
            CookieUtils.setCookie(request, response, pro.getCookieName(), token, this.pro.getExpire() * 30);

            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 出现异常的话，相应500错误
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

}
